package com.astrob.activitys;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.astrob.NavFrameSDK.POIDescription;
import com.astrob.adapters.SearchResultItemAdapter;
import com.astrob.adapters.SearchResultItemAdapter.POIDesc;
import com.astrob.adapters.SearchResultItemAdapter.SeachResultListener;
import com.astrob.model.HistoryData;
import com.astrob.model.LonLat;
import com.astrob.model.Msg;
import com.astrob.model.POITypeObj;
import com.astrob.model.RoutePlanDataHandle;
import com.astrob.model.SearchParm;
import com.astrob.model.SpecialTypeBean;
import com.astrob.model.SpecialTypeBean.onQTItemClickListener;
import com.astrob.naviframe.Start;
import com.astrob.view.SpecialTypeView;
import com.astrob.nhcmap.R;


import java.util.ArrayList;
import java.util.List;

public class SearchAroundActivity extends Activity {
	int mDistance = 500;
	int mTypeIndex = 0;
	SearchResultItemAdapter mAdapter;
	ListView listView;

	int mAddDestMode = -1;
	int mAddDestPos = -1;
	private ArrayList<POITypeObj> mPOITypeObjList = new ArrayList<POITypeObj>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_searcharound);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText(R.string.search_around);
		Bundle bundle = getIntent().getExtras();
		if(bundle != null){
			mAddDestMode = bundle.getInt("mode");
			mAddDestPos = bundle.getInt("pos");
		}
		
		mPOITypeObjList.clear();
		
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search00,
				"All POI", "All POI", getString(R.string.nearsearch_text_all),
				0xffff7d7d));//全部
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search09,
				"07. Tourist", "27. Tourist", getString(R.string.nearsearch_text_9),
				0xff50c7ff));//景点
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search03,
				"03. 酒店", "23. 酒店", getString(R.string.nearsearch_text_3),
				0xff5ada3d));//酒店
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search13,
				"11. Railway Station", "31. Railway Station", getString(R.string.nearsearch_text_13),
				0xff50c7ff));//地铁
		
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search01,
				"01. 餐饮", "21. 餐饮", getString(R.string.nearsearch_text_1),
				0xfffdaa20));//餐饮
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search04,
				"04. Leisure", "24. Leisure", getString(R.string.nearsearch_text_4),
				0xfff072ff));//娱乐
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search02,
				"02. 购物", "22. 购物", getString(R.string.nearsearch_text_2),
				0xff9c70ff));//购物
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search07,
				"06. Bank", "26. Bank", getString(R.string.nearsearch_text_7),
				0xfffdaa20));//银行
		
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search14,
				"16. Airport", "36. Airport", getString(R.string.nearsearch_text_14),
				0xff50c7ff));//机场
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search11,
				"09. Medical", "29. Medical", getString(R.string.nearsearch_text_11),
				0xfffdaa20));//药房
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search12,
				"10.	Public Transport Stop", "30.	Public Transport Stop", getString(R.string.nearsearch_text_12),
				0xff5ada3d));//公交
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search08,
				"12. Petrol Station", "32. Petrol Station", getString(R.string.nearsearch_text_8),
				0xff5ada3d));//加油
		
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search16,
				"15. Hospital", "35. Hospital", getString(R.string.nearsearch_text_16),
				0xff9c70ff));//医疗
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search10,
				"08. Police Station", "28. Police Station", getString(R.string.nearsearch_text_10),
				0xffff7d7d));//警察		
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search15,
				"14. Sport", "34. Sport", getString(R.string.nearsearch_text_15),
				0xfff072ff));//健身
		mPOITypeObjList.add(new POITypeObj(R.drawable.selector_near_search06,
				"05. Post Office", "25. Post Office", getString(R.string.nearsearch_text_6),
				0xffff7d7d));//邮局		

		mAdapter = new SearchResultItemAdapter(this);
		mAdapter.setListener(new SeachResultListener() {
			
			@Override
			public void onRoute(POIDesc poi) {
				HistoryData data = new HistoryData();
				data.name = poi.name;
				data.lon = poi.pos.GetLon();
				data.lat = poi.pos.GetLat();
				data.address = poi.addr;

				RoutePlanDataHandle.getInstance().addDest(data);
				RoutePlanActivity.launch(SearchAroundActivity.this, 3);
			}
			
			@Override
			public void onMap(POIDesc poi) {
				Intent intent = new Intent(SearchAroundActivity.this, NaviActivity.class);
				intent.putExtra("mapcenterlon", poi.pos.GetLon()); //
				intent.putExtra("mapcenterlat", poi.pos.GetLat());
				String poiname = poi.name;
				// 如果是门牌
				if (poiname.contains("路") || poiname.contains("街")) {
					poiname = poi.owner + poiname;
				}
				intent.putExtra("poiname", poiname);
				intent.putExtra("showOnmap", true);
				startActivityForResult(intent, Msg.REQUEST_SHOW_ON_MAP);
			}
			
			@Override
			public void onAround(POIDesc poi) {
				Start.getInstance().MapKit().setMapCenter(new LonLat(poi.pos.GetLon(), poi.pos.GetLat()));
				setResult(Msg.MAP_SEARCHARROUNT);
				finish();
			}
		});
		initUI();
		llcenter_ = Start.getInstance().MapKit().getMapCenter();
		onTypeClick(0);
	}

	SpecialTypeView mgv;
	ArrayList<SpecialTypeBean> mTypeList = null;
	int mPreSelectType = -1; // id must == position	

	private void initUI() {
		mgv = (SpecialTypeView) findViewById(R.id.ms_type_around);		

		mTypeList = new ArrayList<SpecialTypeBean>();
		for (int i = 0; i < mPOITypeObjList.size(); ++i) {
			POITypeObj t = mPOITypeObjList.get(i);
			SpecialTypeBean qtb = new SpecialTypeBean(i, t.resTypeIcon,
					t.strTypeName, t.selectedClr, onQTClick);
			mTypeList.add(qtb);
		}
		mgv.setData(mTypeList);

		listView = (ListView) findViewById(R.id.listview);
		listView.setAdapter(mAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
									long arg3) {
				onListItem(arg2);
			}
		});
	}
	private void doAddRoutePoint(HistoryData data){
		if(mAddDestMode == 3){
			RoutePlanDataHandle.getInstance().addDest(data);
		} else if(mAddDestMode == 2){
			RoutePlanDataHandle.getInstance().changeDest(data, mAddDestPos);
		} else{
			RoutePlanDataHandle.getInstance().setStart(data);
		}
	}
	
	protected void onListItem(int pos) {
		if (pos < 0 || pos >= Start.getInstance().MapKit().mPOIResult.size())
			return;

		POIDescription poi = Start.getInstance().MapKit().mPOIResult.get(pos);

		double lon = Start.getInstance().MapKit().mPOIResult.get(pos).position.lon;
		double lat = Start.getInstance().MapKit().mPOIResult.get(pos).position.lat;

		String name = Start.getInstance().MapKit().mPOIResult.get(pos).name;
		if (name.contains("\n")) {
			String a[] = name.split("\n");
			name = a[0];
		}

		Start.getInstance().MapKit().mTipPoiList = Start.getInstance().MapKit().getNearPoi(
				new LonLat(lon, lat), false);
		Intent intent = new Intent(this, PoiInfoActivity.class);
		intent.putExtra("tipname", poi.name);
		startActivityForResult(intent, Msg.TO_TIPDETAIL);
	}
	
	protected void onListItem2(int pos) {
		if (pos < 0 || pos >= Start.getInstance().MapKit().mPOIResult.size())
			return;
		
		POIDescription poi = Start.getInstance().MapKit().mPOIResult.get(pos);
		
		double lon = poi.position.lon;
		double lat = poi.position.lat;
		String name = poi.name;
		if(mAddDestMode > 0){
			HistoryData data = new HistoryData();
			data.setLl(new LonLat(lon, lat));
			data.setName(name);
			doAddRoutePoint(data);
			setResult(Msg.CHANGE_ROUTEMGR);
			finish();
			return;
		}

		Start.getInstance().MapKit().mTipPoiList = Start.getInstance().MapKit().getNearPoi(
				new LonLat(lon, lat), false);
		Intent intent = new Intent(this, PoiInfoActivity.class);
		intent.putExtra("tipname", poi.name);
		startActivityForResult(intent, Msg.TO_TIPDETAIL);
	}

	onQTItemClickListener onQTClick = new onQTItemClickListener() {
		@Override
		public void onClick(View v, int id) {
			onTypeClick(id);
		}
	};

	private void onTypeClick(int id) {
		if (mPreSelectType >= 0 && mPreSelectType < mTypeList.size()) {
			mTypeList.get(mPreSelectType).setSelected(false);
		}
		
		disIndex = 0;
		mDistance = DIS[disIndex];
		
		mTypeList.get(id).setSelected(true);
		mPreSelectType = id;
		mgv.notifyDataChanged();
		// Toast.makeText(this, "U has clicked "+id, Toast.LENGTH_SHORT).show();
		mTypeIndex = id;
		startQuery();
	}

	public void onBack(View v) {
		setResult(Msg.BACK_MAP_ID);
		finish();
	}

	public void onDistance(int distance) {
		mDistance = distance;
		startQuery();
	}

	ProgressDialog mPB;
	boolean mIsSearching = false;

	int DIS[] = { 500, 1000, 5000, 10000 };
	int disIndex = 0;

	LonLat llcenter_ = new LonLat();

	private void startQuery() {
		if (mIsSearching) {
			return;
		}

		if (!llcenter_.IsValid())
			return;

		mIsSearching = true;
		SearchParm sp = new SearchParm();
		sp.dLon = llcenter_.GetLon();
		sp.dLat = llcenter_.GetLat();
		POITypeObj t = mPOITypeObjList.get(mTypeIndex);
		sp.poiType = t.strType1;
		if (mTypeIndex == 8) {
			//机场范围为100km
			mDistance = 100000;
			disIndex = 3;
		} else {
			disIndex = 0;
			for (int i = 0; i < 4; i++) {
				if (mDistance == DIS[i]) {
					disIndex = i;
					break;
				}
			}
		}			
		sp.range = mDistance;
		
		Start.getInstance().MapKit().mSearchParm = sp;
		if (mPB != null) {
			mPB.cancel();
			mPB = null;
		}
	
		mPB = ProgressDialog.show(this, "正在查询", "查询中...");
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (disIndex < 4) {
					int num = Start.getInstance().MapKit().nearQuery(false);
					if (num != 0)
						break;
					disIndex++;
					if (disIndex < 4) {
						mDistance = DIS[disIndex];
						Start.getInstance().MapKit().mSearchParm.range = mDistance;
					}
				}

				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if (disIndex >= 4)
					disIndex = 3;
				mHandler.sendEmptyMessage(Msg.SEARCHFINISH);
			}
		}).start();
	}

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == Msg.SEARCHFINISH) {
				finishedSearch();
			}
		}

	};

	@Override
	public void finish() {
		if (mPB != null) {
			mPB.dismiss();
			mPB = null;
		}
		super.finish();
	}

	protected void finishedSearch() {
		if (mPB != null) {
			mPB.dismiss();
			mPB = null;
		}

		List<POIDesc> poiList = new ArrayList<POIDesc>();
		LonLat center = Start.getInstance().MapKit().getMapCenter();
		for (int i = 0; i < Start.getInstance().MapKit().mPOIResult.size(); i++) {
			POIDesc item = new POIDesc();
			POIDescription poidata = Start.getInstance().MapKit().mPOIResult.get(i);
			item.name = poidata.name;
			LonLat poill = new LonLat(poidata.position.lon,
					poidata.position.lat);
			item.owner = poidata.owner;
			item.pos = poill;
			item.direct = Start.getInstance().MapKit().getDirection(center, poill);
			int distance = (int) Start.getInstance().MapKit().getDistance(llcenter_, poill);
			item.distance = Start.getInstance().MapKit().getDistanceString(distance);
			item.index = i;

			if (poidata.address != null) {
				item.addr = poidata.address;
			}
			if (poidata.tel != null) {
				item.phone = poidata.tel;
			}
			poiList.add(item);
		}

		mAdapter.setDataList(poiList);
		mAdapter.notifyDataSetChanged();

		mIsSearching = false;
		if (Start.getInstance().MapKit().mPOIResult.size() <= 0) {
			Toast.makeText(this, "查询无结果", Toast.LENGTH_SHORT).show();
		}

		listView.setSelection(0);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			setResult(Msg.BACK_MAP_ID);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == Msg.NAVI_TO_DEST) {
			setResult(Msg.NAVI_TO_DEST);
			finish();
			return;
		} else if (resultCode == Msg.MAP_SEARCHARROUNT) {
			// onTypeClick(0);
			setResult(Msg.MAP_SEARCHARROUNT);
			finish();
			return;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
}

